package com.rabit.test;

/**
 * 设计４个线程，其中两个线程每次对j增加１，另外两个线程每次对ｊ每次减少１，写出程序
 * windos下测试
 * @author rabit
 *
 */
public class MultiThreadShareData {
	private static ShareData1 data1 = new ShareData1();

	public static void main(String[] args) {

		new Thread(new MyRunable1(data1)).start();
		new Thread(new MyRunable2(data1)).start();
		/*
		 * new Thread(new Runnable() {
		 * 
		 * @Override public void run() { data1.decrement();
		 * 
		 * } }).start(); new Thread(new Runnable() {
		 * 
		 * @Override public void run() { data1.increment(); } }).start();
		 */
	}
}

class MyRunable1 implements Runnable {
	private ShareData1 data1;

	public MyRunable1(ShareData1 data1) {
		this.data1 = data1;
	}

	@Override
	public void run() {
		data1.decrement();
	}

}

class MyRunable2 implements Runnable {
	private ShareData1 data1;

	public MyRunable2(ShareData1 data1) {
		this.data1 = data1;
	}

	@Override
	public void run() {
		data1.increment();
	}

}

class ShareData1 implements Runnable {
	private int count = 100;

	@Override
	public void run() {
		while (true) {
			count--;
			System.out.println(count);
		}
	}

	private int j = 100;

	public synchronized void increment() {
		for (int i = 0; i < 20; i++) {
			j++;
			System.out.println(Thread.currentThread().getName()+":  " + j);
		}
	}

	public synchronized void decrement() {
		for (int i = 0; i < 20; i++) {
			j--;
			System.out.println(Thread.currentThread().getName()+":  " + j);
		}
	}

}